import { useState } from 'react'
import { useDispatch } from 'react-redux'
import { Card, Form, Input, Checkbox, Button, message } from 'antd'
import { useHistory, useLocation } from 'react-router-dom'
import logo from '@/assets/logo.png'
import { loginStart } from '@/store/actions/login'
import styles from './index.module.scss'

export default function Login() {
  const history = useHistory()
  const location = useLocation()
  const dispatch = useDispatch()
  const [loading, setLoading] = useState(false)
  const onFinish = async (values) => {
    setLoading(true)
    try {
      await dispatch(loginStart(values))
      message.success('登录成功', 1, () => {
        // location.state 有可能是 undefined
        history.replace(location.state?.from ? location.state.from : '/home')
      })
    } catch (e) {
      message.error(e.response?.data?.message || '网络错误', 1, () =>
        setLoading(false)
      )
    }
  }
  return (
    <div className={styles.root}>
      <Card className='login-container'>
        <img className='login-logo' src={logo} alt='极客园' />
        <Form
          autoComplete='off'
          size='large'
          validateTrigger={['onBlur', 'onChange']}
          initialValues={{
            mobile: '13911111111',
            code: '246810',
            agree: true,
          }}
          onFinish={onFinish}
        >
          {/* 校验规则触发时机：默认提交、输入的时候会触发 */}
          <Form.Item
            name='mobile'
            rules={[
              { required: true, message: '请输入手机号' },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '请输入正确的手机号',
              },
            ]}
          >
            <Input maxLength={11} />
          </Form.Item>

          <Form.Item
            name='code'
            rules={[
              { required: true, message: '请输入验证码' },
              {
                len: 6,
                message: '请输入正确的验证码',
              },
            ]}
          >
            <Input maxLength={6} />
          </Form.Item>

          {/* 默认一上来，checked 是没有的 */}
          {/* 一旦选中 checked => true，有值，不会触发错误校验，ok */}
          {/* 一旦取消选中 checked => false，有值，不会触发错误校验，其实没有选中，期望触发 */}
          {/* 我们真正期望校验的，不是有没有填，而是填的是 true 还是 false */}
          <Form.Item
            valuePropName='checked'
            name='agree'
            rules={[
              {
                validator: (_, value) => {
                  return value
                    ? Promise.resolve()
                    : Promise.reject(new Error('请接收协议'))
                },
              },
            ]}
          >
            <Checkbox>我已阅读并同意[隐私条款]和[用户协议]</Checkbox>
          </Form.Item>

          <Form.Item>
            <Button type='primary' htmlType='submit' block loading={loading}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
